(function (jQuery) {
    //渲染数据
    function renderData(){
        let $num=0;
        let $total=0;
        $("tbody tr").not("tbody tr:last").each(function () {
            $num+=Number($(this).find("[name=txt_num]").val());
            let $price=Number($(this).find("td:eq(5)").text().split("￥")[1]);
            $total+=Number($(this).find("[name=txt_num]").val())*$price;
        })
        $(".topright .count,.rightbar .count").html($num);
        $("tbody .count").html($num);
        $("tbody .total").html("￥"+$total);
    }
    //购物车的初始化
    $(function () {
        if(sessionStorage.getItem("userInfo")==null){
            let cookieList=JSON.parse($.cookie("carts")||'[]');
            if(cookieList.length>=1){
                $(".shopcart_null").hide();
                $(".shopcart").show();
                let str=``;
                let count=0;
                let total=0;
                cookieList.forEach((ele,index)=>{
                    //console.log(ele);
                    str+=`<tr>
									<td width="100" style="border-right: none">
										<a href="list.html?gid=${ele.gid}">
											<img src="${ele.img[0]}" alt="" width="90" height="57">
										</a>
									</td>
									<td width="520" style="border-left: none;text-align: left">${ele.goodsName}</td>
									<td >
									<input type="button" value="-" name="reduce"><input type="text" name="txt_num" value=${ele.num} data-id=${ele.gid}><input type="button" value="+" name="add">
                                    </td>
									<td>￥${ele.newPrice}</td>
									<td>￥0</td>
									<td>￥${ele.newPrice}</td>

									<td>
										<a href="javascript:;;" style="color:#555;" class="del" data-id="${ele.gid}">删除</a>
									</td>
								</tr>`;
                    count+=ele.num;
                    total+=ele.num*Number(ele.newPrice);
                })
                str+=`<tr>
									<td colspan="7" style="text-align: right;font-size: 14px" >
										<span style="margin-right:20px">商品数量： <b class="count" style="color:red;">${count}</b>件</span>
										<span>商品总价（不含邮费）： <b class="total" style="color:red;">￥${total}</b></span>
									</td>
								</tr>`;
                $("tbody").html(str);
            }
        }else{
            let oUser=JSON.parse(sessionStorage.getItem("userInfo"));
            //console.log(oUser[u_id]);
            $.ajax({
                url:"../../server/getCartById.php",
                type:"post",

                data:{u_id:Number(oUser.u_id)}
            }).then(function (res) {
                if(res.length>=1) {
                    $(".shopcart_null").hide();
                    $(".shopcart").show();
                    let str = ``;
                    let count=0;
                    let total=0;
                    res.forEach((ele, index) => {
                        //console.log(ele);
                        str += `<tr>
									<td width="100" style="border-right: none">
										<a href="list.html?gid=${ele.g_id}">
											<img src="${ele.c_img}" alt="" width="90" height="57">
										</a>
									</td>
									<td width="520" style="border-left: none;text-align: left">${ele.c_name}</td>
									<td ><input type="button" value="-" name="reduce"><input type="text" name="txt_num" value=${ele.c_num} data-id=${ele.g_id}><input type="button" value="+" name="add"></td>
									<td>￥${ele.c_price}</td>
									<td>￥0</td>
									<td>￥${ele.c_price}</td>

									<td>
										<a href="javascript:;;" style="color:#555;" class="del" data-id="${ele.g_id}">删除</a>
									</td>
								</tr>`;
                        count+=ele.c_num;
                        total+=ele.c_total;
                    })
                    str+=`<tr>
									<td colspan="7" style="text-align: right;font-size: 14px" >
										<span style="margin-right:20px">商品数量： <b class="count" style="color:red;">${count}</b>件</span>
										<span>商品总价（不含邮费）： <b class="total" style="color:red;">￥${total}</b></span>
									</td>
								</tr>`;
                    $("tbody").html(str);
                }
            })
        }
    })
    //数据的删除
    $(function () {

        $(document).on("click",".del",function () {
            //console.log($(this).data("id"));
            let $self=$(this);
            let d_id=$(this).data("id");
            let i;
            if(sessionStorage.getItem("userInfo")==null){
                let cookieList=JSON.parse($.cookie("carts")||'[]');
                cookieList.forEach((ele,index)=>{
                    if(d_id==ele.gid){
                        i=index;
                    }
                })
                cookieList.splice(i,1);
                $self.parent().parent().remove();
                if($(".shoplist tbody tr").length==1){
                    $(".shoplist").hide();
                    $(".shopcart_null").show();
                }
                $.cookie("carts",JSON.stringify(cookieList));
                renderData();
            }
            else{
                let oUser=JSON.parse(sessionStorage.getItem("userInfo"));
                $.ajax({
                    url:"../../server/delById.php",
                    data:{
                        gid:d_id,
                        uid:oUser.u_id
                    }
                }).then(function (res) {
                    if(res.status==1){
                        alert(res.msg);
                        $self.parent().parent().remove();
                        if($(".shoplist tbody tr").length==1){
                            $(".shoplist").hide();
                            $(".shopcart_null").show();
                        }
                        renderData();
                    }else{
                        alert(res.msg);
                    }
                })
            }
        })
    })
    //数据的修改
    $(function () {

        if(sessionStorage.getItem("userInfo")==null){
            let cookieList=JSON.parse($.cookie("carts")||'[]');
            $(document).on("click","[name=add]",function () {
                let gid=$(this).prev().data("id");

                let num=0;
                num=Number($(this).prev().val())+1;
                $(this).prev().val(num);
                cookieList.forEach((ele,index)=>{
                    if(ele.gid==gid){
                        ele.num=num;
                    }
                })
                $.cookie("carts",JSON.stringify(cookieList));
                renderData();
            })
            $(document).on("click","[name=reduce]",function () {
                let num=0;
                let gid=$(this).next().data("id");
                if(Number($(this).next().val())>1){
                    num=Number($(this).next().val())-1;
                }else{
                    num=1;
                }
                $(this).next().val(num);
                cookieList.forEach((ele,index)=>{
                    if(ele.gid==gid){
                        ele.num=num;
                    }
                })
                $.cookie("carts",JSON.stringify(cookieList));
                renderData();

            })
            $(document).on("blur","[name=txt_num]",function () {
                let num=Number($(this).val());
                let gid=$(this).data("id");
                cookieList.forEach((ele,index)=>{
                    if(ele.gid==gid){
                        ele.num=num;
                    }
                })
                $.cookie("carts",JSON.stringify(cookieList));
                renderData();
            })
        }
        else{
            let oUser=JSON.parse(sessionStorage.getItem("userInfo"));
            $(document).on("click","[name=add]",function () {
                let gid=$(this).prev().data("id");
                let num=0;
                num=Number($(this).prev().val())+1;
                $(this).prev().val(num);
                $.ajax({
                    url:"../../server/updateNum.php",
                    data:{
                        gid:Number(gid),
                        uid:Number(oUser.u_id),
                        num:num
                    }
                }).then(function (res) {
                    renderData();
                })
            })
            $(document).on("click","[name=reduce]",function () {
                let num=0;
                let gid=$(this).next().data("id");
                if(Number($(this).next().val())>1){
                    num=Number($(this).next().val())-1;
                }else{
                    num=1;
                }
                $(this).next().val(num);
                $.ajax({
                    url:"../../server/updateNum.php",
                    data:{
                        gid:gid,
                        uid:oUser.u_id,
                        num:num
                    }
                }).then(function (res) {
                    renderData();
                })


            })
            $(document).on("blur","[name=txt_num]",function () {
                if(Number($(this).val())<1){
                    $(this).val(1);
                }
                let num=Number($(this).val());
                let gid=$(this).data("id");
                $.ajax({
                    url:"../../server/updateNum.php",
                    data:{
                        gid:gid,
                        uid:oUser.u_id,
                        num:num
                    }
                }).then(function (res) {
                    renderData();
                })
            })
        }
    })
})(jQuery)